package com.ias.agdis_r.activity;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.nfc.NfcAdapter;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import androidx.fragment.app.Fragment;
//import android.support.v4.app.FragmentManager;
import androidx.fragment.app.FragmentManager;
//import android.support.v4.app.FragmentTransaction;
import androidx.fragment.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.task.QJMonitorActivity;
import com.ias.agdis_r.activity.task.QJTaskSearchActivity;
import com.ias.agdis_r.activity.task.TaskHisAcitivty;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.fragment.main.MessageListFragment;
import com.ias.agdis_r.fragment.main.Task;
import com.ias.agdis_r.manager.ActionManager;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.util.GPSUtils;
import com.ias.agdis_r.util.NFCUtil;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.TaskUtil;
import com.ias.agdis_r.view.BadgeView;
import com.ias.agdis_r.view.DrawerView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends BaseFragmentActivity implements OnClickListener {

    private static final int[] actionbarLayoutIds = new int[]{R.layout.actionbar_flight, R.layout.actionbar_task,
            R.layout.actionbar_message_list, R.layout.actionbar_more, R.layout.actionbar_mine};
    private static final List<Integer> indicatorBtnIds = Arrays.asList(R.id.main_ll_flight, R.id.main_ll_task,
            R.id.main_ll_xinxi, R.id.main_ll_more, R.id.main_ll_mine);

    private int currentActivePageIndex = -1;
    private ViewGroup indicatorWrapper = null;
    private FrameLayout llflight, lltask, llxinxi, llmore, llmine;
    private ActionBar actionBar = null;
    private ImageView top_head;
    private SlidingMenu slidingMenu;
    private DrawerView drawerView = null;
    public final static String ACTION_TASK = "task";
    public final static String ACTION_MSG = "msg";
    public final static String ACTION_MORE = "more";
    private AlertDialog dialog;
    private FragmentManager fragmentManager = getSupportFragmentManager();
    private BaseFragment fragtask, fragMine;
    private BadgeView BadgeTask, BadgeMessage, BadgeMine;// 任务,信息,个人上的提示红点
    private Spinner spinner_filter;
    private FilterAdapter adapter_filter;
    private boolean able_commit = true;
    private int sortType = TaskUtil.SORT_TIME_DESC;
    public static boolean[] hasTTRTask = new boolean[2];// 记录是否含有转发移交任务
    private boolean backpressIsUsing = false;// back键响应标识，false正常响应，true不响应
    private LinearLayout layout_task_type;
    private final int FRAGMENT_INDEX_FLIGHT = 0;
    private final int FRAGMENT_INDEX_TASK = 1;
    private final int FRAGMENT_INDEX_MSG = 2;
    private final int FRAGMENT_INDEX_MORE = 3;
    private final int FRAGMENT_INDEX_MINE = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        able_commit = true;
        ParameterModel.startMainActivityFlag = true;
        setContentView(R.layout.activity_main);
        init();
        llflight.setOnClickListener(this);
        lltask.setOnClickListener(this);
        llxinxi.setOnClickListener(this);
        llmore.setOnClickListener(this);
        llmine.setOnClickListener(this);

        registerForwardBoradcastReceiver();
		//调用PTT启动广播
        Intent intent = new Intent("ias.ptt.init");
        intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        getApplicationContext().sendBroadcast(intent);
        backpressIsUsing = DataBaseManager.getInstance().getBoolean(ParameterModel.T_KEYPRESS, ParameterModel.BACK_ISUSING);
        NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.NfcNotSupport), false);
        }else if (!mNfcAdapter.isEnabled() && S.valueOf(android.os.Build.MODEL).contains("NDP956")) {
            //610不支持nfc，但是getDefaultAdapter不为空
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.openNfc), false);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_USERCARBIND.toString())) {
            if ("AI_T_USERCARBIND".equals(intent.getStringExtra("AI_T_USERCARBIND"))) {
                NFCUtil.showBindConfirm(this, null);
            }
        }
        if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_GPSINFO.toString())) {
            if ("AI_T_GPSINFO".equals(intent.getStringExtra("AI_T_GPSINFO"))) {
                showGoGPSDialog();
            }
        }
        super.onNewIntent(intent);
    }

    private void showGoGPSDialog() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(MainActivity.this);
        final View dialogView = LayoutInflater.from(MainActivity.this)
                .inflate(R.layout.go_gps_dialog,null);
        customizeDialog.setTitle(getString(R.string.goGPSTitle));
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton(getString(R.string.goGPSSetting),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        GPSUtils.goGPS(MainActivity.this);	// 如果GPS未打开，则跳转GPS设置页。
                        dialog.dismiss();
                    }
                });
        customizeDialog.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        able_commit = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        able_commit = true;
        // 通知BaseFragment刷新
        updateUI(MessageModel.REFRESH);
    }

    @Override
    protected void onStop() {
        able_commit = false;
        super.onStop();
    }

    @Override
    protected void onPause() {
        able_commit = false;
        super.onPause();
    }

    public void registerForwardBoradcastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_TASK);
        filter.addAction(ACTION_MSG);
        filter.addAction(ACTION_MORE);
        registerReceiver(mForwardBroadcastReceiver, filter);
    }

    private BroadcastReceiver mForwardBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_TASK)) {
                selectPage(FRAGMENT_INDEX_TASK);
                if (!actionBar.isShowing()) {
                    actionBar.show();
                }
                initTaskActionbarAction();
            } else if (action.equals(ACTION_MSG)) {
                selectPage(FRAGMENT_INDEX_MSG);
                if (!actionBar.isShowing()) {
                    actionBar.show();
                }
                MessageListFragment messageListFragment = (MessageListFragment) getSupportFragmentManager()
                        .getFragments().get(FRAGMENT_INDEX_MSG);
                messageListFragment.initActionBarEvent();
            } else if (action.equals(ACTION_MORE)) {
                selectPage(FRAGMENT_INDEX_MORE);
                if (!actionBar.isShowing()) {
                    actionBar.show();
                }
            }
        }

    };

    private void init() {
        indicatorWrapper = (ViewGroup) findViewById(R.id.guide_indicator_wrapper);
        layout_task_type = (LinearLayout)findViewById(R.id.layout_task_type);
        llflight = (FrameLayout) findViewById(R.id.main_ll_flight);
        lltask = (FrameLayout) findViewById(R.id.main_ll_task);
        llxinxi = (FrameLayout) findViewById(R.id.main_ll_xinxi);
        llmore = (FrameLayout) findViewById(R.id.main_ll_more);
        llmine = (FrameLayout) findViewById(R.id.main_ll_mine);
        BadgeTask = new BadgeView(MainActivity.this);
        BadgeMessage = new BadgeView(MainActivity.this);
        BadgeMine = new BadgeView(MainActivity.this);
        fragtask = (BaseFragment) fragmentManager.findFragmentById(R.id.frag_task);
        fragMine = (BaseFragment) fragmentManager.findFragmentById(R.id.frag_mine);
        initSildingMenu();
        actionBar = getActionBar();
        selectPage(0);
    }

    /**
     * 切换界面
     *
     * @param index
     */
    public void selectPage(int index) {
        //如果不能切换时，不进行切换
        if(!able_commit){
            return;
        }
        int pageCount = indicatorWrapper.getChildCount();
        // 索引不合法
        if (index < 0 || index > pageCount) {
            return;
        }
        // 为当前页直接返回
        if (currentActivePageIndex == index) {
            return;
        }

        if (index == FRAGMENT_INDEX_TASK || index == FRAGMENT_INDEX_MSG||index == FRAGMENT_INDEX_MORE) {
            if (!ServiceManage.getInstance().getIsLogon()) {
                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.use_function_tologin), false);
                startActivity(new Intent(this, LoginActivity.class));
                return;
            }
        }
        currentActivePageIndex = index;
        List<Fragment> fragments = new ArrayList<Fragment>();
        fragments.add(fragmentManager.findFragmentById(R.id.frag_flight));
        fragments.add(fragmentManager.findFragmentById(R.id.frag_task));
        fragments.add(fragmentManager.findFragmentById(R.id.frag_xinxi));
        fragments.add(fragmentManager.findFragmentById(R.id.frag_more));
        fragments.add(fragmentManager.findFragmentById(R.id.frag_mine));

        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            if (i == index) {
                transaction.show(fragments.get(i));
            } else {
                transaction.hide(fragments.get(i));
            }
        }
        transaction.commit();

        // 更新指示器
        for (int i = 0; i < pageCount; i++) {
            FrameLayout fl = (FrameLayout) indicatorWrapper.getChildAt(i);
            ViewGroup indicator = (ViewGroup) fl.getChildAt(0);
            ImageView img = (ImageView) indicator.getChildAt(0);
            TextView text = (TextView) indicator.getChildAt(1);
            img.setSelected(i == index ? true : false);
            text.setTextColor(i == index ? Color.rgb(19, 142, 234) : Color.rgb(112, 137, 152));
        }
        inflateActionBar(actionbarLayoutIds[index]);
    }

    /**
     * 加载对应页面的actionBar
     *
     * @param layoutId
     */
    private void inflateActionBar(int layoutId) {
        actionBar.setCustomView(LayoutInflater.from(MainActivity.this).inflate(layoutId, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);

        top_head = (ImageView) findViewById(R.id.iv_photo);
        setTop_head();
        if (top_head != null) {
            top_head.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    slidingMenu.toggle();
                }
            });
        }
    }

    private void setTop_head() {
        if (top_head != null) {
            if (ServiceManage.getInstance().getIsLogon()) {
                int id = R.drawable.user_online;
                if(JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_USERCARBIND.toString())){
                    if (S.isEmpty(JavaBeanManager.getInstance().getUserinfo().getVnb())){
                        id = R.drawable.user_online_unbindcar;
                    } else {
                        id = R.drawable.user_online_bindcar;
                    }
                }
                top_head.setImageResource(id);
            } else {
                top_head.setImageResource(R.drawable.user_offline);
            }
        }
    }

    @Override
    public void onClick(View v) {
        // 页面跳转
        int index = indicatorBtnIds.indexOf(v.getId());
        indicatorBtnIds.get(0);
        if (index != -1) {
            selectPage(index);
            if (!actionBar.isShowing()) {
                actionBar.show();
            }
        }
        // 其他
        switch (v.getId()) {
            case R.id.main_ll_flight:
                break;
            case R.id.main_ll_task:
                initTaskActionbarAction();
                break;
            case R.id.main_ll_xinxi:
                try {
                    MessageListFragment messageListFragment = (MessageListFragment) getSupportFragmentManager()
                            .getFragments().get(index);
                    messageListFragment.initActionBarEvent();
                } catch (Exception e) {
                    // TODO: handle exception
                }
                break;
            case R.id.main_ll_more:
                break;
            case R.id.main_ll_mine:
                break;
        }
    }

    private void initTaskActionbarAction() {
        spinner_filter = (Spinner) findViewById(R.id.spinner_filter);
        if (spinner_filter != null) {
            loadSpinnerData();
        }
        ImageView taskMenu = (ImageView) findViewById(R.id.iv_menu);
        if (taskMenu != null) {
            taskMenu.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    showTaskDialog();
                }
            });
        }
    }

    private void showTaskDialog() {
        final List<String> strings = new ArrayList<>();
        strings.add(getString(R.string.taskHis));
        int taskCurrentIndex = -1;
        try {
            taskCurrentIndex = JavaBeanManager.getInstance().getUserinfo().getTaskCurrentIndex();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果不是选中通用任务
        if(taskCurrentIndex!=1) {
            if (JavaBeanManager.getInstance().adjust_pri(
                    AuthEnum.AI_T_TASKMONITOR.toString())) {
                strings.add(getString(R.string.taskMonitor));
            }
            if (JavaBeanManager.getInstance().adjust_pri(
                    AuthEnum.AI_T_TASKSEARCH.toString())) {
                strings.add(getString(R.string.taskSearch));
            }
            List<String> hasTTRList = new ArrayList<>();
            if (hasTTRTask[0]) {
                hasTTRList.add(getString(R.string.taskSendto));
            }
            if (hasTTRTask[1]) {
                hasTTRList.add(getString(R.string.taskTransfer));
            }

            strings.addAll(hasTTRList);
        }
        AlertDialog.Builder bulider = new AlertDialog.Builder(MainActivity.this);
        bulider.setTitle(getString(R.string.chooseOperat));
        bulider.setIcon(android.R.drawable.ic_dialog_info);
        bulider.setSingleChoiceItems(strings.toArray(new String[strings.size()]), 0,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        String item = strings.get(which);
                        if(item.equals(getString(R.string.taskHis))){
                            startActivity(new Intent(MainActivity.this, TaskHisAcitivty.class));
                        }else if(item.equals(getString(R.string.taskMonitor))){
                            startActivity(new Intent(MainActivity.this, QJMonitorActivity.class));
                        }else if(item.equals(getString(R.string.taskSearch))){
                            startActivity(new Intent(MainActivity.this, QJTaskSearchActivity.class));
                        }
                        else if(item.equals(getString(R.string.taskSendto))){
                            // 任务列表开启单选
                            Task task = (Task) fragmentManager.findFragmentById(R.id.frag_task);
                            task.setMultiselect(false);
                            task.setSinglchoice(true);
                        }
                        else if(item.equals(getString(R.string.taskTransfer))){
                            // 任务列表开启多选
                            Task task = (Task) fragmentManager.findFragmentById(R.id.frag_task);
                            task.setSinglchoice(false);
                            task.setMultiselect(true);
                        }
                    }
                });
        bulider.setNegativeButton(getString(R.string.cancel), null);
        dialog = bulider.create();
        dialog.show();
    }

    /**
     * 加载Spinner过滤选择条件
     */
    public void loadSpinnerData() {
        if (adapter_filter == null) {
            List<TaskFilter> spinner_array = new ArrayList<TaskFilter>();
            spinner_array.add(new TaskFilter(TaskUtil.SORT_TIME_ASC, getString(R.string.time1)));
            spinner_array.add(new TaskFilter(TaskUtil.SORT_TIME_DESC, getString(R.string.time2)));
            spinner_array.add(new TaskFilter(TaskUtil.SORT_FLN_ASC, getString(R.string.fln1)));
            spinner_array.add(new TaskFilter(TaskUtil.SORT_FLN_DESC, getString(R.string.fln2)));
            spinner_array.add(new TaskFilter(TaskUtil.SORT_PSN_ASC, getString(R.string.psn1)));
            spinner_array.add(new TaskFilter(TaskUtil.SORT_PSN_DESC, getString(R.string.psn2)));
            spinner_array.add(new TaskFilter(TaskUtil.SORT_STATE_ASC, getString(R.string.state1)));
            spinner_array.add(new TaskFilter(TaskUtil.SORT_STATE_DESC, getString(R.string.state2)));

            adapter_filter = new FilterAdapter(this, spinner_array);
        }
        spinner_filter.setAdapter(adapter_filter);
        spinner_filter.setSelection(MainActivity.this.sortType);
        spinner_filter.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                // TODO Auto-generated method stub
                if (fragtask != null) {
                    TaskFilter filter = adapter_filter.getItem(position);
                    int sortType = filter.id;
                    //保存排序选择
                    MainActivity.this.sortType = sortType;
                    Task frag = (Task) fragtask;
                    //排序
                    frag.sort(sortType);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });
    }

    protected void initSildingMenu() {
        drawerView = new DrawerView(this);
        slidingMenu = drawerView.initSlidingMenu();

//		slidingMenu.setOnOpenedListener(new OnOpenedListener() {
//			
//			@Override
//			public void onOpened() {
//				// TODO Auto-generated method stub
//				if(spinner_filter!=null&&spinner_filter.isShown())
//				{
//					spinner_filter.performClick();
//				}
//			}
//		});
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        unregisterReceiver(mForwardBroadcastReceiver);
        super.onDestroy();
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        // TODO Auto-generated method stub
        if (MessageModel.RELO.equals(serviceId)) {
            updateUI(serviceId);
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.logoutSucceed), false);
        } else if (MessageModel.RELI.equals(serviceId)) {
            updateUI(MessageModel.RELI);
        }

    }

    @Override
    protected void updateUI(String tag) {
        // TODO Auto-generated method stub
        switch (tag) {
            case MessageModel.TTSD:
            case MessageModel.ITSD:
                // 通知BaseFragment刷新
                updateTaskIcon();
                fragtask.updateUI(MessageModel.ITSD);
                break;
            case MessageModel.GWSM:
                break;
            case MessageModel.ITTL:
                break;
            case MessageModel.RKOE:
            case MessageModel.RELO:
                closeDrawerView();
                selectPage(0);
                fragMine.updateUI(tag);
                // 更新任务提示图标
                updateTaskIcon();
                // 更新任务列表显示
                fragtask.updateUI(MessageModel.REFRESH);
                // 更新头像图标
                setTop_head();
                // 刷新消息盒子提示
                ActionManager.getInstance().refreshBox(MessageModel.REFRESH_BOXCLEAN);
                break;
            default:
                // 更新提示图标
                closeDrawerView();
                updateTaskIcon();
                updateMessageIcon();
                updateMineIcon();
                // 更新任务列表显示
                fragtask.updateUI(MessageModel.REFRESH);
                fragMine.updateUI(tag);
                // 更新头像图标
                setTop_head();
                break;
        }

    }

    /**
     * 关闭DrawerView，并更新内容
     */
    public void closeDrawerView() {

        // TODO 注销成功
        if (slidingMenu != null) {
            if (slidingMenu.isMenuShowing()) {
                slidingMenu.toggle();
            }
        }

        if (drawerView != null) {
            drawerView.updateUI();
        }
    }

    /**
     * 检测任务ICON
     */
    private void updateTaskIcon() {
        int newTaskNum = DataManager.getInstance().getReceiveTaskNum()+DataManager.getInstance().getNFReceiveTaskNum();
        lltask.removeView(BadgeTask);
        BadgeTask.setBadgeCount(newTaskNum);
        lltask.addView(BadgeTask);
    }

    /**
     * 检测信息ICON
     */
    private void updateMessageIcon() {
        int newTaskNum = DataManager.getInstance().getUnreadMsgNum();
        // 更换图标显示
        llxinxi.removeView(BadgeMessage);
        BadgeMessage.setBadgeCount(newTaskNum);
        llxinxi.addView(BadgeMessage);
    }

    /**
     * 检测个人ICON
     */
    private void updateMineIcon() {
        // llmine.removeView(BadgeMine);
        // BadgeMine.setBadgeCount(count);
        // llmine.addView(BadgeMine);
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        moveTaskToBack(true);
    }

    class FilterAdapter extends BaseAdapter {
        private List<TaskFilter> mList;
        private Context mContext;

        public FilterAdapter(Context pContext, List<TaskFilter> pList) {
            this.mContext = pContext;
            this.mList = pList;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public TaskFilter getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater _LayoutInflater = LayoutInflater.from(mContext);
            convertView = _LayoutInflater.inflate(R.layout.task_filter_spinner_item, null);
            if (convertView != null) {
                TextView txt = (TextView) convertView.findViewById(android.R.id.text1);
                txt.setText(mList.get(position).name);
            }
            return convertView;
        }
    }

    class TaskFilter {
        public TaskFilter(int id, String name) {
            this.id = id;
            this.name = name;
        }

        int id;
        String name;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (backpressIsUsing && keyCode == KeyEvent.KEYCODE_BACK){
            return true;
        }else{
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onMenuKeyDown() {
        //如果当前显示的fragment是任务界面
        if(currentActivePageIndex==FRAGMENT_INDEX_TASK){
            if (dialog == null || !dialog.isShowing()){
                showTaskDialog();
            }
        }
    }
}
